<template>
  <c-view>
    <template v-slot:header>
      <div class="title">
        {{ $route.meta.title }}
      </div>
    </template>
    <div class="main__box">
      <c-table
        ref="cTable"
        selection
        hasBorder
        :max-height="maxHeight"
        :size="size"
        :loading="isLoading"
        :table-header="tableHeader"
        :table-list="tableList"
        :table-inner-btns="tableInnerBtns"
        :page-info="pageInfo"
        @change-pagination="changePagination"
      >
        <template v-slot:header>
          <c-search :form-model="searchObj" :form-items="searchItems" @submit-form="searchSubmit" @reset-form="searchReset"></c-search>
          <el-button-group class="btn-group">
            <el-button type="primary" :size="size" icon="el-icon-plus" @click="showDialog">新增优惠券</el-button>
            <el-button type="primary" :size="size" icon="el-icon-connection" @click="bindBatchNoDialog">绑定批次号</el-button>
          </el-button-group>
        </template>
      </c-table>
    </div>
    <div v-if="dialogObj.isShow">
      <c-dialog
        class="dialog-box"
        :is-show="dialogObj.isShow"
        :title="dialogObj.title"
        close-btn
        @before-close="dialogObj.isShow = false"
        @on-submit="dialogConfirm"
      >
        <coupon-add v-if="dialogObj.showType === 1" ref="childRef" :init-data.sync="dialogObj.initData"></coupon-add>
        <coupon-bind v-if="dialogObj.showType === 2" ref="childRef" :init-data.sync="dialogObj.initData" show-type="2"></coupon-bind>
        <coupon-bind
          v-if="dialogObj.showType === 3"
          ref="childRef"
          :init-data.sync="dialogObj.initData"
          show-type="3"
          :batch-no="dialogObj.batchNo"
        ></coupon-bind>
      </c-dialog>
    </div>
  </c-view>
</template>

<script>
import mixinTable from 'mixins/table'
import CDialog from 'components/dialog'
import dictObj from '@/store/dictData'
import CouponAdd from './add'
import CouponBind from './bind'
import utils from 'utils'

export default {
  name: 'coupon',
  mixins: [mixinTable],
  components: {
    CDialog,
    CouponAdd,
    CouponBind
  },
  data(vm) {
    return {
      // 对话框对象
      dialogObj: {},
      // 表格内操作按钮
      tableInnerBtns: [
        {
          name: '绑定客户',
          width: 210,
          icon: 'el-icon-connection',
          handle(row) {
            const { couponCode } = row
            vm.showDialog({
              title: '优惠券绑定客户',
              isShow: true,
              showType: 2,
              initData: {
                couponCode
              }
            })
          }
        },
        {
          name: '作废',
          icon: 'el-icon-document-delete',
          handle(row) {
            const { id, couponCode, title } = row
            vm.confirmTip(`是否废除【${title}（${couponCode}）】优惠券`, () => {
              vm.cancelHandle({ id, status: 2 })
            })
          }
        },
        {
          name: '删除',
          icon: 'el-icon-delete',
          handle(row) {
            const { couponCode, id, title } = row
            vm.confirmTip(`是否删除【${title}（${couponCode}）】优惠券`, () => {
              vm.deleteHandle({ id })
            })
          }
        }
      ],
      tableHeader: [
        {
          label: '优惠券编码',
          prop: 'couponCode',
          fixed: true,
          search: {
            type: 'input'
          },
          width: 100
        },
        {
          label: '优惠券名称',
          prop: 'title',
          width: 100
        },
        {
          label: '优惠券额度(元)',
          prop: 'money',
          formatter: row => row && utils.formatMoney(row.money),
          width: 120
        },
        {
          label: '批次号',
          prop: 'batchNo',
          width: 130,
          search: {
            type: 'input'
          }
        },
        {
          label: '用户名称',
          prop: 'memberName',
          width: 100
        },
        {
          label: '用户手机号',
          prop: 'memberPhone',
          width: 110,
          search: {
            type: 'input'
          }
        },
        {
          label: '发券模式',
          prop: 'category',
          formatter: row => (row ? (row.category === 1 ? '自动' : '手动') : '未知'),
          width: 100
        },
        // {
        //   label: '发券类型',
        //   prop: 'categoryCode',
        //   width: 100
        // },
        {
          label: '优惠券状态',
          prop: 'status',
          formatter: row => row && vm.setTableColumnLabel(row.status, 'couponStatus'),
          search: {
            type: 'dict',
            optionsList: dictObj.couponStatus
          },
          width: 100
        },
        {
          label: '使用状态',
          prop: 'usedStatus',
          formatter: row => row && vm.setTableColumnLabel(row.usedStatus, 'couponUsedStatus'),
          width: 100,
          search: {
            type: 'dict',
            optionsList: dictObj.couponUsedStatus
          }
        },
        {
          label: '描述',
          prop: 'description',
          inline: true
        },
        {
          label: '所属区域',
          prop: 'cityName',
          width: 100
        },
        {
          label: '有效开始时间',
          prop: 'startTime',
          width: 160
        },
        {
          label: '有效结束时间',
          prop: 'endTime',
          width: 160
        },
        {
          label: '创建时间',
          prop: 'createTime',
          width: 160
        }
      ]
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    /*
     * 查询表格列表数据
     */
    fetchData() {
      const { pageNo, pageSize } = this.pageInfo
      const { dateTime, ...other } = this.searchObj
      const searchDate = this.getSearchDate(dateTime)
      this.isLoading = true
      this.$api.marketing
        .fetch('couponList', {
          ...searchDate,
          ...other,
          rows: pageNo,
          offset: pageSize
        })
        .then(res => {
          this.isLoading = false
          if (res && res.totalCount) {
            const { data, totalCount } = res
            this.pageInfo.totalNum = totalCount
            this.tableList = data || []
          } else {
            this.tableList = res || []
          }
        })
    },
    /**
     * dialog对话框数据处理
     * @opts {*}
     */
    showDialog(opts) {
      this.dialogObj = {
        isShow: true,
        showType: opts.showType || 1,
        isBatchNo: opts.isBatchNo || false, // 是否批次
        title: opts.title || '新增优惠券',
        initData: opts.initData
      }
    },
    // 绑定批次号对话框
    bindBatchNoDialog() {
      this.dialogObj = {
        isShow: true,
        showType: 3,
        title: '绑定批次号'
      }
    },
    /**
     * dialog新增、编辑处理函数
     */
    dialogConfirm() {
      const childRef = this.$refs.childRef
      childRef.$refs.formRef.validate(valid => {
        if (valid) {
          const { showType } = this.dialogObj
          if (showType === 2 || showType === 3) {
            const { curPhone, couponCode, batchNo } = childRef.formModel
            if (curPhone) {
              if (curPhone.length === 11 || (curPhone.length > 11 && curPhone.indexOf(',') !== -1)) {
                if (curPhone.length === 11 && utils.isMobile(curPhone) && showType === 2) {
                  this.$api.marketing.fetch('bingCoupon', { memberPhone: curPhone, couponCode }).then(() => {
                    this.responeHandle(`绑定${curPhone}成功`)
                  })
                } else {
                  if (showType === 3) {
                    let errPhone = ''
                    curPhone.split(',').forEach(val => {
                      if (!utils.isMobile(val)) {
                        errPhone = val
                      }
                    })
                    if (errPhone) {
                      return this.$msgTip(`${errPhone}手机号码异常`, 'warning')
                    }
                    this.$api.marketing.fetch('bindGroupCoupon', { phoneList: curPhone, batchNo }, { hasErrMsg: true }).then(res => {
                      const { code, message } = res
                      if (code != -1) {
                        this.responeHandle(message || `批量绑定手机号成功`)
                      } else {
                        this.$msgTip(message, 'warning')
                      }
                    })
                  }
                }
              } else {
                if (curPhone.indexOf('，') != -1) {
                  this.$msgTip('请输入正确的分割符号', 'warning')
                } else if (!utils.isMobile(curPhone)) {
                  this.$msgTip('请输入有效手机号码', 'warning')
                }
              }
            } else {
              this.$msgTip('手机号不能为空', 'warning')
            }
          } else {
            const { dateTime, money, ...other } = childRef.formModel
            const startTime = dateTime[0]
            const endTime = dateTime[1]
            this.$api.marketing.fetch('saveOrUpdateCoupon', { startTime, endTime, money: money * 100, ...other }).then(() => {
              this.responeHandle('新增优惠券成功')
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    /**
     * 删除单条表格数据
     * @params {object} 接口参数
     */
    deleteHandle(params) {
      this.$api.marketing.fetch('deleteCoupon', params).then(() => {
        this.$msgTip('删除成功')
        this.delResetData()
      })
    },
    /**
     * 删除单条表格数据
     * @id {Number}
     */
    cancelHandle(params) {
      this.$api.marketing.fetch('invalidCoupon', params).then(() => {
        this.responeHandle('优惠券作废成功')
      })
    }
  }
}
</script>
